let host;
function request(url, method, data, header = {
  'Content-Type': 'application/x-www-form-urlencoded'
},file) {
  wx.showLoading({
    title: '加载中' //数据请求前loading
  })
  return new Promise((resolve, reject) => {
      var urls = '';
      if (url == '/hyApi/initServer'){
        urls = 'https://www.mopai8.com/wo' + url
      } else if (data.host) {
        urls = data.host + url
      }else{
        urls = host + url;
      }
      if (header["Content-Type"] && header["Content-Type"] == "multipart/form-data"){
          wx.uploadFile({
            url: urls,
            filePath: file,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            formData:data,
            success: function (res) {
              wx.hideLoading();
              resolve(res.data)
            },
            fail: function (error) {
              wx.hideLoading();
              reject(false)
            },
            complete: function () {
              wx.hideLoading();
            }
          })
      }else{
        wx.request({
          url: urls, //仅为示例，并非真实的接口地址
          method: method,
          data,
          header,
          success: function (res) {
            wx.hideLoading();
            resolve(res.data)
            if (data && data.host) {
              host = data.host;
            }
            if (res && res.header && res.header['Set-Cookie']) {
              wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
            }
            if (res.data.s == 3 && url != '/common/login') {
              /* wx.redirectTo({
                url: `/pages/login/main`
              }) */
            }
          },
          fail: function (error) {
            wx.hideLoading();
            reject(false)
          },
          complete: function () {
            wx.hideLoading();
          }
        })
      }
      
  })
}
function get(obj) {
  return request(obj.url, 'GET', obj.data,obj.header)
}
function post(obj) {
  return request(obj.url, 'POST', obj.data,obj.header)
}
function upload(obj) {
  return request(obj.url, 'POST', obj.data, obj.header,obj.file)
}
export default {
  upload,
  request,
  get,
  post,
  host
}